<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示信息 -->
      <el-row>
        <el-alert
          show-icon
          :closable="false"
          title="注意：只允许为第三级分类设置相关参数"
          type="warning"
        >
        </el-alert>
      </el-row>

      <!-- 选择商品分类级联选择器 -->
      <el-row class="opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择框 options用来指定数据源  props用来指定配置对象
          clearable 是否可以清空-->
          <el-cascader
            clearable
            v-model="selectedKeys"
            :options="classifyList"
            :props="classifyProps"
            @change="classifyChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- 商品分类表格区域 -->
      <el-row>
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <!-- 动态参数面板 -->
          <el-tab-pane label="动态参数" name="many">
            <!-- 添加参数按钮 -->
            <el-button
              :disabled="isBtnDisabled"
              class="addbtn"
              type="primary"
              @click="addDialogVisible = true"
              >添加参数
            </el-button>

            <!-- 动态参数表格 -->
            <el-table :data="manyParamsList" border stripe style="width: 100%">
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    :key="index"
                    v-for="(value, index) in scope.row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(scope.row, index)"
                  >
                    {{ value }}
                  </el-tag>
                  <!-- 输入的文本框 -->
                  <el-input
                    class="input-new-tag "
                    v-if="scope.row.editManyParamsInputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveManyParamsRef"
                    size="small"
                    @keyup.enter.native="saveManyParams(scope.row)"
                    @blur="saveManyParams(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showEditManyParamsInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <!-- 索引列 -->
              <el-table-column type="index"> </el-table-column>
              <el-table-column prop="attr_name" label="参数名称">
              </el-table-column>
              <el-table-column label="操作">
                <!-- 操作模板 -->
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    @click="showEditDialog(scope.row.attr_id)"
                    icon="el-icon-edit"
                    >编辑
                  </el-button>
                  <el-button
                    type="danger"
                    @click="deleteParams(scope.row.attr_id)"
                    icon="el-icon-delete"
                    >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!--静态属性面板 -->
          <el-tab-pane label="静态属性" name="only">
            <!-- 添加属性按钮 -->
            <el-button
              :disabled="isBtnDisabled"
              class="addbtn"
              type="primary"
              @click="addDialogVisible = true"
              >添加属性
            </el-button>

            <!-- 静态属性表格 -->
            <el-table :data="onlyParamsList" border stripe style="width: 100%">
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    :key="index"
                    v-for="(value, index) in scope.row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(scope.row, index)"
                  >
                    {{ value }}
                  </el-tag>
                  <!-- 输入的文本框 -->
                  <el-input
                    class="input-new-tag "
                    v-if="scope.row.editManyParamsInputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveManyParamsRef"
                    size="small"
                    @keyup.enter.native="saveManyParams(scope.row)"
                    @blur="saveManyParams(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showEditManyParamsInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <!-- 索引列 -->
              <el-table-column type="index"> </el-table-column>
              <el-table-column prop="attr_name" label="属性名称">
              </el-table-column>
              <el-table-column label="操作">
                <!-- 操作模板 -->
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    @click="showEditDialog(scope.row.attr_id)"
                    icon="el-icon-edit"
                    >编辑
                  </el-button>
                  <el-button
                    type="danger"
                    @click="deleteParams(scope.row.attr_id)"
                    icon="el-icon-delete"
                    >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-row>

      <!-- 添加对话框 -->
      <el-dialog
        :title="'添加' + dialogTitle"
        @close="addDialogClose"
        :visible.sync="addDialogVisible"
        width="50%"
      >
        <el-form
          :model="addForm"
          ref="addFormRef"
          :rules="addFormRules"
          label-width="100px"
        >
          <el-form-item :label="dialogTitle" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定 </el-button>
        </span>
      </el-dialog>

      <!-- 编辑对话框 -->
      <el-dialog
        :title="'编辑' + dialogTitle"
        @close="editDialogClose"
        :visible.sync="editDialogVisible"
        width="50%"
      >
        <el-form
          :rules="editFormRules"
          :model="editForm"
          ref="editFormRef"
          label-width="100px"
        >
          <el-form-item :label="dialogTitle" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //分类列表
      classifyList: [],
      //级联选择框的配置信息
      classifyProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true, // 来设置父子节点取消选中关联，从而达到选择任意一级选项的目的。
        disabled: true
      },
      //级联选择框选中的分类的id
      selectedKeys: [], //[1, 4, 24], 设置一个默认值 方便测试
      //默认选择第一个标签
      activeName: 'many',
      //动态分类参数列表
      manyParamsList: [],
      //静态分类参数列表
      onlyParamsList: [],
      //控制添加对话框是否显示
      addDialogVisible: false,
      //控制修改对话框是否显示
      editDialogVisible: false,
      //添加表单
      addForm: {
        attr_name: ''
      },
      //编辑表单
      editForm: {},
      //添加分类表单的验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 编辑分类表单的验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getClassifyList()
    // this.getParamsData()  方便测试
  },
  methods: {
    async getClassifyList() {
      const { data: response } = await this.$axios.get('categories')
      if (response.meta.status !== 200)
        return this.$message.error('获取商品分类失败')
      this.classifyList = response.data
      //   console.log(response.data)
      return this.$message.success(response.meta.msg)
    },
    //分类选项发生变化时触发
    async classifyChange() {
      //   console.log(this.selectedKeys)
      this.getParamsData()
    },
    // tab页签点击事件的处理函数
    handleTabClick() {
      //   console.log(this.activeName)
      this.getParamsData()
    },
    // 获取参数列表
    async getParamsData() {
      //只允许为第三级分类设置相关参数 则this.selectedKeys.length只能为3
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyParamsList = ''
        this.onlyParamsList
        return
      }
      // 证明选中的是三级分类
      //   console.log(this.selectedKeys)

      const { data: response } = await this.$axios.get(
        `categories/${this.classifyId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )

      if (response.meta.status !== 200)
        return this.$message.error('获取分类参数失败')

      response.data.forEach(item => {
        //先判断item.attr_vals是否存在
        //若存在再分割字符串 否则返回空数组 防止出现空标签
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        //控制文本框的显示与隐藏
        item.editManyParamsInputVisible = false
        // 文本框中输入的值
        item.inputValue = ''
      })
      this.manyParamsVals = response.data.attr_vals
      //   console.log(response.data)
      //   判断是动态数据还是静态数据
      if (this.activeName === 'many') {
        this.manyParamsList = response.data
      } else {
        this.onlyParamsList = response.data
      }
      this.$message.success('获取分类成功')
    },
    //添加对话框处理函数
    async addParams() {
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return
        const { data: response } = await this.$axios.post(
          'categories/' + this.classifyId + '/attributes',
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        // console.log(this.addForm)
        if (response.meta.status !== 201)
          return this.$message.error('添加' + this.dialogTitle + '失败')

        // console.log(response)
        this.getParamsData()
        //隐藏添加分类对话框
        this.addDialogVisible = false
        this.$message.success('添加' + this.dialogTitle + '成功')
      })
    },
    // 显示修改动态参数面板并查询参数
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: response } = await this.$axios.get(
        'categories/' + this.classifyId + '/attributes/' + id,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      )
      //   console.log(response)
      if (response.meta.status !== 200)
        return this.$message.error('查询' + this.dialogTitle + '失败')

      this.editForm = response.data
      this.$message.success('查询' + this.dialogTitle + '成功')
    },
    // 修改参数对话框处理函数
    async editParams() {
      this.$refs.editFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return
        const { data: response } = await this.$axios.put(
          'categories/' +
            this.classifyId +
            '/attributes/' +
            this.editForm.attr_id,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (response.meta.status !== 200)
          return this.$message.error('修改' + this.dialogTitle + '失败')

        // console.log(response)
        this.getParamsData()
        //隐藏添加分类对话框
        this.editDialogVisible = false
        this.$message.success('修改' + this.dialogTitle + '成功')
      })
    },
    // 关闭添加对话框时触发
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 关闭编辑对话框时触发
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    //删除动态参数
    async deleteParams(id) {
      await this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: response } = await this.$axios.delete(
            'categories/' + this.classifyId + '/attributes/' + id
          )

          if (response.meta.status !== 200)
            return this.$message.error('删除属性失败')

          this.getParamsData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //点击按钮 显示修改参数输入框
    showEditManyParamsInput(row) {
      row.editManyParamsInputVisible = true
      //使文本框自动获得焦点
      //$nextTick 当页面上元素被重新渲染之后 才会执行回调函数中的代码
      // 如果没有渲染 则不存在refs 会报错
      this.$nextTick(_ => {
        this.$refs.saveManyParamsRef.$refs.input.focus()
      })
    },
    //保存修改的参数 文本框失去焦点或者使用ENTER 都会触发
    async saveManyParams(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.editManyParamsInputVisible = false
        return
      }
      //添加文本框的内容到数组中
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.editManyParamsInputVisible = false
      //截至到这里 都只是将数据添加到了页面上 而没有存储再数据库中
      // 所有要发送请求 保存数据
      this.saveAttrVals(row)
    },
    //处理标签的删除事件
    handleClose(row, index) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    },
    async saveAttrVals(row) {
      const { data: response } = await this.$axios.put(
        'categories/' + this.classifyId + '/attributes/' + row.attr_id,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        }
      )
      if (response.meta.status !== 200)
        return this.$message.error('修改' + this.dialogTitle + '失败')

      // console.log(response)
      //   this.getParamsData()
      this.$message.success('修改' + this.dialogTitle + '成功')
    }
  },
  computed: {
    //当按钮被禁用时 返回true 否则返回false
    isBtnDisabled() {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    classifyId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    // 对话框的标题
    dialogTitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.addbtn {
  float: left;
  margin-bottom: 20px;
}
.el-tag {
  margin: 10px;
}
.opt {
  margin: 20px 0;
}
.el-cascader {
  width: 50%;
}
.input-new-tag {
  width: 120px;
}
</style>
